define(
  'sf.b2c.mall.module.price', [
    'can',
    'zepto',
    'underscore',
    'sf.b2c.mall.api.product.getPrices',
    'sf.b2c.mall.api.shopcart.addItemsToCart',
    'sf.b2c.mall.framework.comm',
    'sf.b2c.mall.widget.cartnumber'
  ],

  function(can, $, _, SFGetPrices, SFAddItemToCart, SFFrameworkComm, SFWidgetCartNumber) {
    SFFrameworkComm.register(3);
    var price = can.Control.extend({
      init: function(element, options) {
        this.render(element);
      },
      render: function(element) {
        var that = this;
        var itemIds = this.getItemList();
        // 如果不存在itemid 直接返回
        if (!_.isArray(itemIds) || itemIds.length <= 0) {
          return false;
        }
        // 渲染
        can.when(this.requestPrices(itemIds))
          .done(function(data) {
            // 如渲染价格
            that.renderPrice(data, element);
          })
          .fail(function(errorCode) {
            console.error(errorCode);
          })
      },

      /**
       * [renderPrice 渲染价格]
       * @param  {[type]} data [description]
       * @return {[type]}      [description]
       */
      renderPrice: function(data, element) {
        var that = this;
        _.each(data.value, function(value, key, list) {
          var itemIds = element.find("[data-cms-itemid='" + value.id + "']")
          if (itemIds.length && itemIds.length > 1) {
            _.each(itemIds, function(item) {
              that.fillPrice($(item), value);
            })
          } else {
            that.fillPrice(itemIds, value);
          }
        });
      },

      /**
       * [fillPrice 填充价格]
       * @param  {[type]} element [description]
       * @param  {[type]} value   [description]
       * @return {[type]}         [description]
       */
      fillPrice: function(element, value) {
        // 售价
        element.find('.cms-fill-price').text(value.p / 100);
        // 如果原价低于卖价，则不展示折扣和原价
        if (value.p >= value.m || value.m == null) {
          element.find('.cms-fill-discountparent').hide();
          element.find('.cms-fill-referencepriceparent').hide();
        } else {
          element.find('.cms-fill-referenceprice').text(value.m / 100);
          element.find('.cms-fill-discount').text((parseInt(value.p, 10) * 10 / parseInt(value.m, 10)).toFixed(1));
        }
        // 做售空处理
        if (value.stk == 0) {
          element.find('.cms-fill-gotobuy').text('已经抢光');
          var status = element.find('.cms-fill-status');
          if (status && status.length && status.length > 0) {
            element.find(".cms-fill-status").append('<div class="mask"><span class="icon icon5 center">售完</span></div>');
          } else {
            element.find(".cms-fill-soldout").show();
          }
        }
      },

      getItemList: function() {
        var $el = this.element.find('.cms-src-item');
        var ids = [];
        _.each($el, function(el) {
          var id = $(el).attr('data-cms-itemid');
          if (!_.isEmpty(id)) {
            ids.push(window.parseInt(id));
          }
        });
        return _.uniq(ids);
      },

      requestPrices: function(itemIds) {
        var request = new SFGetPrices({
          itemIds: JSON.stringify(itemIds)
        });
        return request.sendRequest();
      },

      /**
       * @description 添加购物车动作触发
       * @param  {element} el
       */
      '[data-cart=addtocart] click': function(el, event) {
        event && event.preventDefault();
        var that = this;
        var itemId = el.parents("li[data-cms-itemid]").data("cmsItemid");
        if (SFFrameworkComm.prototype.checkUserLogin.call(this)) {
          //向服务器端发送加入购物车的请求
          can.when(this.addCart(itemId))
            .done(function(data) {
              if (data.isSuccess) {
                setTimeout(function() {
                  can.trigger(window, 'updateCart');
                  that.updateCart();
                }, 1000);
                that.showMsg("添加成功!");
              } else {
                that.showMsg(data.resultMsg);
              }
            });
        } else {
          window.location.href = 'http://m.tepin.hk/user/login.html?from=' + encodeURIComponent(window.location.href);
        }
      },

      showMsg: function(msg) {
        var $el = $('<section style="position:fixed" class="tooltip center overflow-num"><div>' + msg + '</div></section>');
        $(document.body).append($el);
        setTimeout(function() {
          $el.remove();
        }, 2500);
      },
      /**
       * @author Michael.Lee
       * @description 加入购物车
       */
      addCart: function(itemId, num) {
        var addItemToCart = new SFAddItemToCart({
          items: JSON.stringify([{
            itemId: itemId,
            num: num || 1
          }])
        });

        // 添加购物车发送请求
        return addItemToCart.sendRequest()
          .done(function(data) {})
          .fail(function(data) {
            if (data == 15000800) {
              var $el = $('<section style="position:fixed" class="tooltip center overflow-num"><div>您的购物车已满，赶紧去买单哦～</div></section>');
              $(document.body).append($el);
              setTimeout(function() {
                $el.remove();
              }, 2500);
            }
          });
      },

      /**
       * @author Michael.Lee
       * @description 更新导航栏购物车，调用接口刷新购物车数量
       */
      updateCart: function() {
        var that = this;
        // 如果用户已经登陆了，可以进行购物车更新
        // @todo 如果是白名单的用户可以看到购物车
        if (SFFrameworkComm.prototype.checkUserLogin.call(this)) {
          this.element.find('.mini-cart-num').show();

          var success = function(data) {
            $(".mini-cart-num").text(data.value);
          };

          var error = function() {
            // 更新mini cart失败，不做任何显示
          };
          new SFWidgetCartNumber(success, error);
        }
      }
    });
    // // 查到所有需要渲染价格的模块
    // var priceModules = $('.cms-module-fillprice');

    // // 分别进行实例化
    // _.each(priceModules, function(priceModule) {
    //   new price($(priceModule));
    // });
    var priceModules = $('.cms-module-fillprice');

    var getPriceList = function(priceModules) {
      var currentView;
      var headerHeight = $('.header').height();
      _.each(priceModules, function(priceModule) {
        currentView = $(priceModule).position().top;
        if ($(window).scrollTop() == 0) {
          if (window.screen.height > currentView) {
            if (!$(priceModule).hasClass("price-loaded")) {
              $(priceModule).addClass("price-loaded");
              new price($(priceModule));
            }
          }
        } else {
          if ($(window).scrollTop() + window.screen.height > currentView) {
            if (!$(priceModule).hasClass("price-loaded")) {
              $(priceModule).addClass("price-loaded");
              new price($(priceModule));
            }
          }
        }
      });
    };

    new getPriceList(priceModules);
    $(window).scroll(function() {
      new getPriceList(priceModules);
    });
  });